package com.loy;
import com.aspose.words.*;

public class TestReplaceTable2 {
    private static String word_A="D:\\java\\数据文件.docx";
    private static String word_B="D:\\java\\表格模板.docx";
    private static String out_path="D:\\java\\2222222222222222test.docx";

    public static void main(String[] args) throws Exception {
        // 加载文档
        Document docA = new Document(word_A);
        Document docB = new Document(word_B);

        // 1. 定位WordA第二页的表格及其确切位置
        TablePosition position = locateTableInPage(docA, 2);
        if (position == null || position.targetTable == null) {
            System.out.println("未在WordA第二页找到表格");
            return;
        }

        // 2. 获取WordB的第二个表格
        Table replacementTable = getNthTable(docB, 1);
        if (replacementTable == null) {
            System.out.println("WordB中没有第二个表格");
            return;
        }

        // 3. 执行安全替换
        safeReplaceTable(docA, position, replacementTable);

        // 4. 保存结果
        docA.save(out_path);
        System.out.println("表格已精准替换并保存到output.docx");
    }

    // 表格位置信息封装
    private static class TablePosition {
        public Table targetTable;
        public CompositeNode parent;
        public int childIndex;
    }

    // 安全定位表格位置
    private static TablePosition locateTableInPage(Document doc, int pageNum) throws Exception {
        TablePosition result = new TablePosition();
        LayoutCollector layoutCollector = new LayoutCollector(doc);

        // 获取文档中所有节点
        NodeCollection<Node> nodes = doc.getChildNodes(NodeType.ANY, true);

        for (int i = 0; i < nodes.getCount(); i++) {
            Node node = nodes.get(i);
            if (node.getNodeType() == NodeType.TABLE) {
                int tablePage = layoutCollector.getStartPageIndex(node);
                if (tablePage + 1 == pageNum) {
                    result.targetTable = (Table)node;
                    result.parent = (CompositeNode)node.getParentNode();
                    result.childIndex = getChildIndex(result.parent, node);
                    return result;
                }
            }
        }
        return null;
    }

    // 获取节点在父节点中的索引
    private static int getChildIndex(CompositeNode parent, Node child) {
        for (int i = 0; i < parent.getChildNodes().getCount(); i++) {
            if (parent.getChildNodes().get(i) == child) {
                return i;
            }
        }
        return -1;
    }

    // 安全替换表格
    private static void safeReplaceTable(Document doc, TablePosition position,
                                         Table newTableSource) throws Exception {
        // 导入新表格
        Table newTable = (Table)doc.importNode(newTableSource, true);
        CompositeNode parent = position.parent;

        // 方法1：使用childIndex直接替换（最可靠）
//        parent.getChildNodes().set(position.childIndex, newTable);

//         方法2（备选）：如果方法1不适用，使用以下方案
         Node refNode = position.childIndex < parent.getChildNodes().getCount() - 1
             ? parent.getChildNodes().get(position.childIndex + 1)
             : null;

         if (refNode != null) {
             parent.insertBefore(newTable, refNode);
         } else {
             parent.appendChild(newTable);
         }
         parent.removeChild(position.targetTable);

        // 复制格式
        copyTableFormat(position.targetTable, newTable);
    }

    // 复制表格格式
    private static void copyTableFormat(Table source, Table target) throws Exception {
        target.setStyleIdentifier(source.getStyleIdentifier());
        target.setAlignment(source.getAlignment());
        target.setPreferredWidth(source.getPreferredWidth());
    }

    // 获取第N个表格
    private static Table getNthTable(Document doc, int n) {
        NodeCollection<Table> tables = doc.getChildNodes(NodeType.TABLE, true);
        return tables.getCount() >= n ? (Table) tables.get(n-1) : null;
    }
}
